package weaver.tools.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.axis.encoding.Base64;
import org.apache.commons.io.IOUtils;
import weaver.alioss.AliOSSObjectManager;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocServiceImpl;
import weaver.file.AESCoder;
import weaver.general.BaseBean;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.cese.duss.ceseutil.OcrUitl;
import weaver.interfaces.datasource.DataSource;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * @Title: Ecology9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2024-04-15
 * @Description: 文档、附件工具类
 * @ModifyLog:
 **/

public class DocUtil {

    /**
     *@Description: 创建文档单附件
     */
    public static int createImagefile(int userid, InputStream input, String rawFileName, int seccategory) {
        BaseBean log = new BaseBean();
        byte[] content = null;
        // 上传附件，创建html文档
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        DocAttachment[] docattachment = new DocAttachment[1];
        String docsubject = ""; //文档标题
        String keyword = ""; //文档内容
        String filetype = "";
        String filename = "";
        if (rawFileName.lastIndexOf(".") > -1) {
            filetype = rawFileName.substring(rawFileName.lastIndexOf(".") + 1);
            filename = rawFileName.substring(0, rawFileName.lastIndexOf("."));
        }
        try {
            content =  IOUtils.toByteArray(input);
            DocAttachment da = new DocAttachment();
            da.setFilename(filename + "." + filetype);//附件标题
            da.setFilecontent(Base64.encode(content)); //附件内容
            da.setFiletype(filetype); //imagefiletype
            da.setImagefilename(filename + "." + filetype);// 附件标题
            da.setIszip(1);//是否压缩
            da.setIsAesEncrype(0);//是否加密
            da.setAesCode("0");
            da.setIsextfile("1"); //附件是否是office类型
            if (filetype.equalsIgnoreCase("doc")) {
                da.setDocfiletype("3");
            } else if (filetype.equalsIgnoreCase("xls")) {
                da.setDocfiletype("4");
            } else if (filetype.equalsIgnoreCase("ppt")) {
                da.setDocfiletype("5");
            } else if (filetype.equalsIgnoreCase("wps")) {
                da.setDocfiletype("6");
            } else if (filetype.equalsIgnoreCase("docx")) {
                da.setDocfiletype("7");
            } else if (filetype.equalsIgnoreCase("xlsx")) {
                da.setDocfiletype("8");
            } else if (filetype.equalsIgnoreCase("pptx")) {
                da.setDocfiletype("9");
            } else {
                da.setDocfiletype("2");
            }
            docattachment[0] = da;
            docsubject = filename;
            keyword = filename;
            DocInfo doc = new DocInfo();//创建文档
            doc.setSeccategory( seccategory );//子目录id
            doc.setDocSubject(docsubject);//标题
            doc.setDoccontent("");//文档内容
            doc.setKeyword(keyword);
            doc.setAttachments(docattachment);
            if (!"".equals(userid)) {
                User user = new User(userid);
                docid = docserviceimpl.createDocByUser(doc, user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.writeLog("e:" + e);
        }
        return docid;
    }


    /**
     *@Description: 创建文档单附件
     */
    public static int createDoc(int userid, InputStream input, String rawFileName, int seccategory) {
        BaseBean log = new BaseBean();
        byte[] content = new byte[102400];
        // 上传附件，创建html文档
        content = null;
        try {
            int byteread;
            byte data[] = new byte[1024];
            //InputStream input = new FileInputStream(new File(path));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((byteread = input.read(data)) != -1) {
                out.write(data, 0, byteread);
                out.flush();
            }
            content = out.toByteArray();
            input.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        DocAttachment[] docattachment = new DocAttachment[1];
        String docsubject = ""; //文档标题
        String keyword = ""; //文档内容
        String filetype = "";
        String filename = "";
        if (rawFileName.lastIndexOf(".") > -1) {
            filetype = rawFileName.substring(rawFileName.lastIndexOf(".") + 1);
            filename = rawFileName.substring(0, rawFileName.lastIndexOf("."));
        }
        try {
            DocAttachment da = new DocAttachment();
            da.setFilename(filename + "." + filetype);//附件标题
            da.setFilecontent(Base64.encode(content)); //附件内容
            da.setFiletype(filetype); //imagefiletype
            da.setImagefilename(filename + "." + filetype);// 附件标题
            da.setIszip(1);//是否压缩
            da.setIsAesEncrype(0);//是否加密
            da.setAesCode("0");
            da.setIsextfile("1"); //附件是否是office类型
            if (filetype.equalsIgnoreCase("doc")) {
                da.setDocfiletype("3");
            } else if (filetype.equalsIgnoreCase("xls")) {
                da.setDocfiletype("4");
            } else if (filetype.equalsIgnoreCase("ppt")) {
                da.setDocfiletype("5");
            } else if (filetype.equalsIgnoreCase("wps")) {
                da.setDocfiletype("6");
            } else if (filetype.equalsIgnoreCase("docx")) {
                da.setDocfiletype("7");
            } else if (filetype.equalsIgnoreCase("xlsx")) {
                da.setDocfiletype("8");
            } else if (filetype.equalsIgnoreCase("pptx")) {
                da.setDocfiletype("9");
            } else {
                da.setDocfiletype("2");
            }
            docattachment[0] = da;
            docsubject = filename;
            keyword = filename;
            DocInfo doc = new DocInfo();//创建文档
            //doc.setMaincategory(41);//主目录id
            //doc.setSubcategory(6042);//分目录id
            doc.setSeccategory( seccategory );//子目录id
            doc.setDocSubject(docsubject);//标题
            doc.setDoccontent("");//文档内容
            doc.setKeyword(keyword);
            doc.setAttachments(docattachment);
            if (!"".equals(userid)) {
                User user = new User(userid);
                docid = docserviceimpl.createDocByUser(doc, user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.writeLog("e:" + e);
        }
        return docid;
    }

    /**
     *@Description: 创建文档多附件
     */
    public static int createDocs(String userid,int seccategory, List<Map<String, String>> list) {
        BaseBean log = new BaseBean();
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        String docsubject = ""; //文档标题
        String keyword = ""; //文档内容
        try {
            if (list.size() > 0) {
                DocAttachment[] docattachment = new DocAttachment[list.size()];
                for (int i = 0; i < list.size(); i++) {
                    Map<String, String> datamap = list.get(i);
                    String rawFileName = Util.null2String(datamap.get("rawFileName"));
                    log.writeLog("rawFileName:" + rawFileName);
                    String filetype = "";
                    log.writeLog("rawFileName:" + rawFileName.lastIndexOf("."));
                    if (rawFileName.lastIndexOf(".") > -1) {
                        filetype = rawFileName.substring(rawFileName.lastIndexOf(".") + 1);
                    }
                    log.writeLog("filetype:" + filetype);
                    String content = datamap.get("content");
                    DocAttachment da = new DocAttachment();
                    da.setFilename(rawFileName);//附件标题
                    da.setFilecontent(content); //附件内容
                    da.setFiletype(filetype); //imagefiletype
                    da.setImagefilename(rawFileName);// 附件标题
                    da.setIszip(1);//是否压缩
                    da.setIsAesEncrype(0);//是否加密
                    da.setAesCode("0");
                    da.setIsextfile("1"); //附件是否是office类型

                    if (filetype.equalsIgnoreCase("doc")) {
                        da.setDocfiletype("3");
                    } else if (filetype.equalsIgnoreCase("xls")) {
                        da.setDocfiletype("4");
                    } else if (filetype.equalsIgnoreCase("ppt")) {
                        da.setDocfiletype("5");
                    } else if (filetype.equalsIgnoreCase("wps")) {
                        da.setDocfiletype("6");
                    } else if (filetype.equalsIgnoreCase("docx")) {
                        da.setDocfiletype("7");
                    } else if (filetype.equalsIgnoreCase("xlsx")) {
                        da.setDocfiletype("8");
                    } else if (filetype.equalsIgnoreCase("pptx")) {
                        da.setDocfiletype("9");
                    } else {
                        da.setDocfiletype("2");
                    }
                    docattachment[i] = da;
                    docsubject = rawFileName;
                    keyword = rawFileName;
                }
                DocInfo doc = new DocInfo(); //创建文档
                doc.setSeccategory(seccategory);//子目录id
                doc.setDocSubject(docsubject);//标题
                doc.setDoccontent("");//文档内容
                doc.setKeyword(keyword);
                doc.setAttachments(docattachment);
                log.writeLog("userid:" + userid);
                if (!"".equals(userid)) {
                    User user = new User(Util.getIntValue(userid));
                    docid = docserviceimpl.createDocByUser(doc, user);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return docid;
    }

    /**
     *@Description: 获取邮件附件
     */
    public static void queryMailFile(String filepath, String iszip){
        DataSource ds = (DataSource) StaticObj.getServiceByFullname(("datasource.local"), DataSource.class);
        Connection conn = null;
        try {
            conn = ds.getConnection();
            String sql = " update mail_middleinfo set filecontent=? where id=? ";
            PreparedStatement pstm = conn.prepareStatement(sql);
            InputStream inputstream = null;
            ZipInputStream zin = null;
            try {
                File docfile = new File(filepath);
                if ("0".equals(iszip)) {
                    inputstream = new BufferedInputStream(new FileInputStream(docfile));
                } else {
                    zin = new ZipInputStream(new FileInputStream(docfile));
                    if (zin.getNextEntry() != null) {
                        inputstream = new BufferedInputStream(zin);
                    }
                }
                pstm.clearParameters();
                pstm.setBinaryStream(1, inputstream);
                pstm.addBatch();
                if (zin != null) {
                    zin.close();
                }

                if (inputstream != null) {
                    inputstream.close();
                }
            } catch (Exception e) {
            } finally {
                if (inputstream != null) {
                    inputstream.close();
                }

                if (zin != null) {
                    zin.close();
                }
            }
            pstm.executeBatch();
            conn.close();
        } catch (Exception e) {
        } finally {
            try {
                conn.close();
            } catch (Exception e) {

            }
        }
    }

    /**
     *@Description: 获取附件内容
     */
    public static byte[] getContent(int fileId) {
        byte[] content = new byte[102400];
        // 上传附件，创建html文档
        content = null;
        try {
            int byteread;
            byte data[] = new byte[1024];
            InputStream input = OcrUitl.getInputStreamById(fileId);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((byteread = input.read(data)) != -1) {
                out.write(data, 0, byteread);
                out.flush();
            }
            content = out.toByteArray();
            input.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     *@Description: 获取imagefileldid（文件id
     */
    private Map<String, String> getImageFileldInfo(int docId) {
        Map<String, String> map = new HashMap<>();
        String imagefileid = "0";
        String imagefilename = "";
        String sql = "SELECT imagefileid,imagefilename FROM DocImageFile where docid = " + docId;
        RecordSet rs = new RecordSet();
        rs.execute(sql);
        if (rs.next()) {
            imagefileid = rs.getString("imagefileid");
            if (imagefileid.equals("") || imagefileid.equals("-1")) {
                imagefileid = "0";
            }
            imagefilename = rs.getString("imagefilename");
        }
        map.put("imagefilename", imagefilename);
        map.put("imagefileid", imagefileid);
        return map;
    }

    /**
     *@Description: 创建文件
     */
    public static boolean createFile(int imagefileid, String distFilePath) {
        boolean status = true;
        InputStream inputStream = getInputStreamById(imagefileid);
        int index;
        byte[] bytes = new byte[1024];
        try {
            FileOutputStream downloadFile = new FileOutputStream(distFilePath);
            while ((index = inputStream.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
            inputStream.close();
            downloadFile.close();
        } catch (Exception e) {
            status = false;
            e.printStackTrace();
        }
        return status;
    }

    /**
     * 获取签字意见附件信息
     */
    public static JSONArray getImageFile(String docids) {
        BaseBean baseBean = new BaseBean();
        RecordSet rs = new RecordSet();
        JSONArray fileList = new JSONArray();
        baseBean.writeLog(">>>>>getImageFile>>>>>docids=" + docids);
        rs.executeQuery("select imagefileid,imagefilename from DocImageFile where docid in (" + docids + ")");
        while (rs.next()) {
            JSONObject dataJson = new JSONObject();
            int imagefileid = Util.getIntValue(rs.getString("imagefileid"), -1);
            String imagefilename = Util.null2String(rs.getString("imagefilename"));
            dataJson.put("name", imagefilename);
            baseBean.writeLog(">>>>imagefileid=" + imagefileid);
            baseBean.writeLog(">>>>imagefilename=" + imagefilename);
            try {
                InputStream inputStream = getInputStreamById(imagefileid);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024 * 100];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }
                byteArrayOutputStream.flush();
                dataJson.put("value", byteArrayOutputStream.toByteArray());
            } catch (Exception e) {
                e.printStackTrace();
            }
            fileList.add(dataJson);
        }
        return fileList;
    }

    /**
     *@Description: 返回文件流   已经经过脱密、解压
     */
    public static InputStream getInputStreamById(int imageFileId) {
        InputStream imagefile = null;
        try {
            RecordSet rs = new RecordSet();
            String sql = "select fileRealPath,isZip,isaesencrypt,aescode,tokenKey,storageStatus  from ImageFile where imageFileId =?";
            rs.executeQuery(sql,imageFileId);
            if (rs.next()) {
                String static_fileRealPath = Util.null2String(rs.getString("fileRealPath"));
                String static_isZip = Util.null2String(rs.getString("isZip"));
                int static_isaesencrypt = Util.getIntValue(rs.getString("isaesencrypt"), 0);
                String static_aescode = Util.null2String(rs.getString("aescode"));
                String static_tokenKey = Util.null2String(rs.getString("tokenKey"));
                String static_storageStatus = Util.null2String(rs.getString("storageStatus"));
                boolean isonlyAliOSS = false;
                if (!static_tokenKey.equals("") && static_storageStatus.equals("1") && AliOSSObjectManager.isonlyAliOSS()) {
                    isonlyAliOSS = true;
                }

                if (isonlyAliOSS) {
                    imagefile = weaver.alioss.AliOSSObjectUtil.downloadFile(static_tokenKey);
                } else {
                    if (static_fileRealPath != null && !static_fileRealPath.equals("")) {
                        File thefile = new File(static_fileRealPath);
                        if (static_isZip.equals("1")) {
                            ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile));
                            if (zin.getNextEntry() != null) {
                                imagefile = new BufferedInputStream(zin);
                            }
                        } else {
                            imagefile = new BufferedInputStream(new FileInputStream(thefile));
                        }
                    } else {
                        ConnStatement statement = null;
                        try {
                            statement = new ConnStatement();
                            boolean isoracle = ("oracle").equals(statement.getDBType());
                            statement.setStatementSql("select imagefile from ImageFile where imagefileid = " + imageFileId);
                            statement.executeQuery();
                            if (statement.next()) {
                                if (isoracle) {
                                    imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile"));
                                } else {
                                    imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile"));
                                }
                            }
                        } catch (Exception ex) {
                        } finally {
                            try {
                                if (statement != null) {
                                    statement.close();
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                    if (static_isaesencrypt == 1) {
                        imagefile = AESCoder.decrypt(imagefile, static_aescode);
                    }

                }
            }


        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return imagefile;
    }

    /**
     *@Description: 获取文件路径
     */
    public static String getFilePath(String docid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select filerealpath from imagefile where imagefileid in (select imagefileid from docimagefile where docid = '" + docid + "')" );
        rs.next();
        return Util.null2String( rs.getString( "filerealpath" ) );
    }

}
